package org.wutopia.examples.randomprot.utility;


import java.io.IOException;
import java.net.Socket;
import java.util.Random;

public class ServerPortUtils {
    public static int getAvailablePort(int min, int max) {
        Random random = new Random();
        int maxAttempts = max - min;
        while (maxAttempts-- > 0) {
            int port = min + random.nextInt(max - min);
            if (!isPortInUse("127.0.0.1", port)) {
                return port;
            }
        }
        throw new IllegalStateException("无可用端口");
    }

    private static boolean isPortInUse(String host, int port) {
        try (Socket ignored = new Socket(host, port)) {
            return true;  // 端口已被占用
        } catch (IOException e) {
            return false; // 端口可用
        }
    }
}
